﻿using GTMC.Model;
using ScanConfirm.Business;
using ScanConfirm.Enum;
using ScanConfirm.Handle;
using ScanConfirm.Model;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ScanConfirmForm
{
    public partial class FrmMain : Form
    {
        ScanConfirmHandler scanConfirmHandler;
        public FrmMain()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //检查是否多开
            string processName = Process.GetCurrentProcess().ProcessName;
            Process[] processes = Process.GetProcessesByName(processName);
            //如果该数组长度大于1，说明多次运行
            if (processes.Length > 1)
            {
                MessageBox.Show("程序已运行，不能再次打开！");
                Environment.Exit(1);
            }
            //全屏，覆盖任务栏
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.FormBorderStyle = FormBorderStyle.None;
                this.WindowState = FormWindowState.Maximized;
            }

            scanConfirmHandler = ScanConfirmHandler.getInstance();
            scanConfirmHandler.MesgNotificationEvent += MesgShow;
            var result = scanConfirmHandler.Init();
            if(!result)
            {
                MessageBox.Show("系统初始化失败，请检查后再尝试运行！");
                //Application.Exit();
            }
            timer1.Start();
            scanConfirmHandler.OnWorkQueueChange += OnWorkQueueChange;
            scanConfirmHandler.OnScanInput += ScanInfoRefresh;
            scanConfirmHandler.OnDeviceChange += OnDeviceChange;
           

            for (int i = 0; i < scanConfirmHandler.DeviceList.Count; i++)
            {
                var device = scanConfirmHandler.DeviceList[i];
                pl_top_2.Controls.Find("txtDeviceState" + i, true).Last().Visible = true;
                pl_top_2.Controls.Find("txtDeviceState" + i, true).Last().Text = device.Name;
                if (device.State)
                    pl_top_2.Controls.Find("txtDeviceState" + i, true).Last().BackColor = Color.LimeGreen;
                else
                    pl_top_2.Controls.Find("txtDeviceState" + i, true).Last().BackColor = Color.OrangeRed;
            }

            dgvQueue.ClearSelection();
            dgvQueue.AutoGenerateColumns = false;
            dgvQueue.ReadOnly = true;
            dgvQueue.AddColumn("车型", "CarModelCode", 33);
            dgvQueue.AddColumn("连番", "Sequence", 33);
            if (scanConfirmHandler.SysSetup.CheckType == "PartsCode")
                dgvQueue.AddColumn("品番", "DisplayCode", 34);
            else if (scanConfirmHandler.SysSetup.CheckType == "Mark")
                dgvQueue.AddColumn("记号", "DisplayCode", 34);

            if (scanConfirmHandler.SysSetup.CheckType == "PartsCode")
                lableCheckType.Text = "品番";
            else if (scanConfirmHandler.SysSetup.CheckType == "Mark")
                lableCheckType.Text = "记号";


            //根据屏幕分辩率计算调整控件位置及大小
            int width = (pl_shipment_content.Width - 20) / 2;
            int height = pl_shipment_content.Height - 10;
            //int columnHeight = height / ((scanConfirmHandler.SysSetup.QueueCount + 2));
            int columnHeight = height / ((10 + 2));
            panelTitle1.Location = new Point(10 , 10);
            panelTitle1.Width = width-10;
            panelTitle1.Height = columnHeight;
            panelTitle2.Location = new Point(10 + width, 10);
            panelTitle2.Width = width;
            panelTitle2.Height = columnHeight;
            panelTitle3.Location = new Point(10, 600);
            panelTitle3.Width = width-10;
            panelTitle3.Height = columnHeight;
            txtInfo.Location = new Point(10, 610+ columnHeight);
            txtInfo.Width= width - 10;
            txtInfo.Height = height - columnHeight - 590;
            dgvQueue.Location = new Point(10 + width, 10 + columnHeight);
            dgvQueue.Width = width;
            dgvQueue.Height = height - columnHeight;
            dgvQueue.RowHeight = columnHeight;
            dgvQueue.ColumnHeadersHeight = columnHeight;

            int topWidth = pl_top.Width;
            pl_top_1.Width = topWidth / 2;
            int bottomWidth = pl_bottom.Width;
            pl_bottom_2.Width = bottomWidth / 2;
            DgvRefresh(scanConfirmHandler.CurrentWorkQueues);
            CurrentWorkInfoRefresh(scanConfirmHandler.CurrentWorkQueues);
            MesgShow("系统初始化...", MessageType.Info);
        }

        private void OnDeviceChange(List<DeviceModel> list)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                for (int i = 0; i < list.Count; i++)
                {
                    var device = list[i];
                    pl_top_2.Controls.Find("txtDeviceState" + i, true).Last().Visible = true;
                    pl_top_2.Controls.Find("txtDeviceState" + i, true).Last().Text = device.Name;
                    if (device.State)
                        pl_top_2.Controls.Find("txtDeviceState" + i, true).Last().BackColor = Color.LimeGreen;
                    else
                        pl_top_2.Controls.Find("txtDeviceState" + i, true).Last().BackColor = Color.OrangeRed;
                }
            }));
        }

        public void OnWorkQueueChange(List<QueueInfoModel> queue)
        {
            try
            {
                DgvRefresh(queue);
                Thread.Sleep(500);
                CurrentWorkInfoRefresh(queue);
            }
            catch(Exception ex) { }
        }

        public void CurrentWorkInfoRefresh(List<QueueInfoModel> queue)
        {
            var model = queue.Where(x => x.Status == "work" || x.Status == "unok").FirstOrDefault();
            if (model == null)
                return;
            this.Invoke(new MethodInvoker(() =>
            {
                txtSequence.Text = model.Sequence.ToString();
                txtVehicleModel.Text = model.CarModelCode;
                if (scanConfirmHandler.SysSetup.CheckType == "PartsCode")
                    txtMark.Text = model.PartsCode;
                else if (scanConfirmHandler.SysSetup.CheckType == "Mark")
                    txtMark.Text = model.Mark;
                txtScan.FillColor = Color.White;
                txtScan.Text = "";
            }));
        }

        public void ScanInfoRefresh(string str, bool result)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                txtScan.Text = str;
                if (result)
                {
                    if (string.IsNullOrEmpty(str))
                        txtScan.FillColor = Color.White;
                    else
                        txtScan.FillColor = Color.LightGreen;
                }
                else
                {
                    txtScan.FillColor = Color.OrangeRed;
                }
            }));
        }

        public void DgvRefresh(List<QueueInfoModel> queue)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                dgvQueue.DataSource = queue;
                Dgv_Cells(ref dgvQueue);
            }));
        }

        public void Dgv_Cells(ref UIDataGridView dgv)
        {
            if (dgv.Rows.Count > 0)
                dgv.Rows[0].Selected = false;

            foreach (DataGridViewRow item in dgv.Rows)
            {
                var model = item.DataBoundItem as QueueInfoModel;
                if (model.Status == "ok")
                {
                    item.DefaultCellStyle.BackColor = Color.LightGray;
                }
                else if(model.Status == "work")
                {
                    item.DefaultCellStyle.BackColor = Color.LightGreen;
                }else if(model.Status == "unok")
                {
                    item.DefaultCellStyle.BackColor = Color.Red;
                }
                else if (model.Status == "pass")
                {
                    item.DefaultCellStyle.BackColor = Color.Yellow;
                }
                else
                {
                    item.DefaultCellStyle.BackColor = Color.White;
                }
            }
        }

        /// <summary>
        /// 实时消息显示
        /// </summary>
        /// <param name="mes">显示消息</param>
        /// <param name="index">消息类型(0错误信息；1正常信息)</param>
        private void MesgShow(string mes, MessageType messageType)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                switch(messageType)
                {
                    case MessageType.Error:
                        AppendTextColorful(this.txtInfo, mes, Color.Red, true);
                        break;
                    case MessageType.TopError:
                        AppendTextColorful(this.txtInfo, mes, Color.Red, true,true);
                        break;
                    case MessageType.Info:
                        AppendTextColorful(this.txtInfo, mes, Color.Green, true);
                        break;
                    case MessageType.warning:
                        AppendTextColorful(this.txtInfo, mes, Color.Yellow, true);
                        break;

                }
                    
            }));
        }

        /// <summary>
        /// 富文本框格式化方法
        /// </summary>
        /// <param name="rtBox">富文本框</param>
        /// <param name="addtext">添加文本内容</param>
        /// <param name="color">当前添加文本显示颜色</param>
        /// <param name="IsaddNewLine">是否换行</param>
        /// <param name="IsTop">是否显示在最顶部</param>
        private void AppendTextColorful(RichTextBox rtBox, string addtext, Color color, bool IsaddNewLine,bool IsTop=false)
        {
            if (IsaddNewLine)
            {
                addtext += Environment.NewLine;
            }
            if(IsTop)
                rtBox.SelectionStart = 0;
            else
                rtBox.SelectionStart = rtBox.TextLength;

            rtBox.SelectionLength = 0;
            rtBox.SelectionColor = color;

            if (IsTop)
            {
                rtBox.SelectedText = DateTime.Now.ToString() + "  " + addtext;
                rtBox.ScrollToCaret();
            }
            else
                rtBox.AppendText(DateTime.Now.ToString() + "  " + addtext);

            rtBox.SelectionColor = rtBox.ForeColor;

            if(rtBox.Lines.Length > 5000&&!IsTop)
            {
                DelSpecialLines(rtBox, 1, 500);//删除第 1 行
            }

            rtBox.Refresh();
            rtBox.Focus();
        }

        /// <summary>
        /// 删除任意指定行
        /// </summary>
        /// <param name="startLineNum">开始行号</param>
        /// <param name="endLineNum">结束行号</param>
        private void DelSpecialLines(RichTextBox rtBox, int startLineNum, int endLineNum)
        {
            //获取指定行的第一行的第一个字符的索引
            int start = rtBox.GetFirstCharIndexFromLine(startLineNum - 1);

            //获取指定行的最后一行的第一个字符的索引
            int end = rtBox.GetFirstCharIndexFromLine(endLineNum);
            rtBox.Select(start, end - start);//选中指定行
            rtBox.SelectedText = "";//设置选择行的内容为空
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.ShowDialog();
            if (frmLogin.DialogResult == DialogResult.OK)
            {
                if (scanConfirmHandler.User.Permission == 0)
                {
                    var mesg = "用户(" + scanConfirmHandler.User.LoginName + ")操作：关闭软件！";
                    MesgShow(mesg, MessageType.Info);
                    scanConfirmHandler.LogInfo(mesg);
                    Application.Exit();
                }
                else
                {
                    var mesg = "用户(" + scanConfirmHandler.User.LoginName + ")操作：关闭软件禁止！禁止原因：无此权限！";
                    MesgShow(mesg, MessageType.Error);
                    scanConfirmHandler.LogError(mesg);
                    MessageBox.Show("该用户权限无法进行此操作！");
                }
            }
        }

        private void btnRecord_Click(object sender, EventArgs e)
        {
            FrmHistory frmHistory = new FrmHistory();
            frmHistory.Show();
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.ShowDialog();
            if (frmLogin.DialogResult == DialogResult.OK)
            {
                if (scanConfirmHandler.User.Permission == 0)
                {
                    FrmSetup frmSetup = new FrmSetup();
                    frmSetup.Show();
                }
                else
                {
                    var mesg = "用户(" + scanConfirmHandler.User.LoginName + ")操作：系统设置禁止！禁止原因：无此权限！";
                    MesgShow(mesg, MessageType.Error);
                    scanConfirmHandler.LogError(mesg);
                    MessageBox.Show("该用户权限无法进行此操作！");
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void btnForcedSkip_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.ShowDialog();
            if (frmLogin.DialogResult == DialogResult.OK)
            {
                if(scanConfirmHandler.User.Permission == 0)
                {
                    scanConfirmHandler.CoerceSkip();
                }
                else
                {
                    var mesg = "用户(" + scanConfirmHandler.User.LoginName + ")操作：强制跳过禁止！禁止原因：无此权限！";
                    MesgShow(mesg, MessageType.Error);
                    scanConfirmHandler.LogError(mesg);
                    MessageBox.Show("该用户权限无法进行此操作！");
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            txt_systime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var result = scanConfirmHandler.SqlConnectionState();
            MessageBox.Show(result.ToString());
            //scanConfirmHandler.LogDebug($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 开始");
            //Task<string> task =  Task.Factory.StartNew<string>(()=> {
            //    Thread.Sleep(2000);
            //    return "123";
            //});
            //scanConfirmHandler.LogDebug($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} {task.Result}");
            //scanConfirmHandler.LogDebug($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} 结束");
        }

        private void dgvQueue_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            frmLogin.Show();
        }

        int many = 100;
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            MessageBoxButtons mess = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("刷新将跳过系统缓存的未作业连番，并重新以POKAYOKE下一个连番为第一个连番获取作业队列，确定要刷新吗？", "提示", mess);
            if (dr == DialogResult.OK)
            {
                scanConfirmHandler.RefreshQueueInfo();
            }
            //PokayokeModel pokayokeModel = new PokayokeModel();
            //pokayokeModel.VIN = "LVGDD4A40RG170615";
            //pokayokeModel.BodyNo = "AB" + many;
            //pokayokeModel.AssemblySequenceNo = many++;
            //pokayokeModel.ProgramNo =new int[16]{2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
            //scanConfirmHandler.Pokayoka_OnReceiveProdInsNotify("", pokayokeModel);
        }
    }
}
